import java.util.Arrays;

public class Work01 {
    public int lastStoneWeight(int[] stones) {
        Arrays.sort(stones);
        int length = stones.length;
        while(length > 1){
            length = smash(stones,length);
            Arrays.sort(stones);
        }
        if(length == 0){
            return 0;
        }else{
            return stones[0];
        }
    }

    private int smash(int[] stones,int length){
        int x = stones[length-1];
        int y = stones[length - 2];
        if(x == y){
            length = length -2;
        }else if(x < y){
            stones[length -2] = y-x;
            length = length - 1;
        }else{
            stones[length - 2] = x - y;
            length -= 1;
        }
        return length;
    }

}
